var common = require("../../data/posts-data.js");
Page({
  onLoad: function (options) {
    var readings = this.getReadingsFormStorge();
    var postList = common.postList;
    for (var i = 0; i < readings.length; i++) {
      var reading = readings[i];
      for (var j = 0; j < postList.length; j++) {
        var post = postList[j];
        if (reading.postId === post.postId) {
          post.reading = reading.reading;
        }
      }
    }
    this.setData({ posts: postList });
  },
  gotoPostDetailFormSwiper: function (event) {
    var that = this;
    // target 指的是被点击的组件
    // currentTarget 指的是截获事件的组件
    var postId = event.target.dataset.postId;
    wx.navigateTo({
      url: 'post-detail/post-detail?id=' + postId,
      success: function () {
        // 保存查看数量至本地缓存中
        that.saveReadingCountToStorge(postId);
        // 刷新UI中的查看数量
        that.refreshUI(postId);
      }
    });
  },
  gotoPostDetail: function (event) {
    var that = this;
    var postId = event.currentTarget.dataset.postId;
    var posts = this.data.posts;

    this.changeBackground(posts, postId,true);
    setTimeout(function () {
      that.changeBackground(posts, postId,false);
      wx.navigateTo({
        url: 'post-detail/post-detail?id=' + postId,
        success: function () {
          // 保存查看数量至本地缓存中
          that.saveReadingCountToStorge(postId);
          // 刷新UI中的查看数量
          that.refreshUI(postId);
        }
      });
    }, 200);

  },
  changeBackground: function (posts,postId, show) {
    posts[postId].itemClick = show;
    this.setData({ posts: posts });
  },
  refreshUI: function (postId) {
    var posts = this.data.posts;
    var post = posts[postId];
    post.reading = post.reading + 1;
    this.setData({ posts, posts });
  },
  saveReadingCountToStorge: function (postId) {
    //获取本地存在的记录
    var readings = wx.getStorageSync('readings');
    //本地记录是否空
    if (readings) {//不为空
      //记录状态
      var isExit = false;
      //进行遍历，如果postId已经存在本地则获取并更新
      for (var i = 0; i < readings.length; i++) {
        var reading = readings[i];
        if (reading.postId === postId) {
          reading.reading = reading.reading + 1;
          isExit = true;
          break;
        }
      }
      if (!isExit) {
        readings.push({ postId: postId, reading: 1 });
      }
    } else {
      readings = [{ postId: postId, reading: 1 }];
    }
    wx.setStorageSync('readings', readings)
  },
  getReadingsFormStorge: function () {
    var readings = wx.getStorageSync('readings');
    return readings;
  }
})